/**
 *   This file is part of JGroove.
 *
 *   JGroove is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   JGroove is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *   GNU Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public License
 *   along with JGroove. If not, see <http://www.gnu.org/licenses/>.
 **/

package jgroove;

import jgroove.jsonx.*;
import com.google.gson.Gson;
import java.util.HashMap;

import java.net.URL;
import java.net.URLConnection;
import java.io.OutputStreamWriter;
import java.io.InputStream;

import java.net.MalformedURLException;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;

/**
 * Abstract class with easy and quick methods to communicate and have real fun
 * with Grooveshark
 * @author Aitor Ruano Miralles <0x077d@gmail.com>
 */
public class JGroovex {

    /**
     * Returns the results of a search from the result of calling
     * Grooveshark's method getSearchResultsEx
     * @param query Words to search
     * @param type The type of result you want (Songs, Artits, Albums, Playlists...)
     * @return Json object with al info of the response
     * @throws MalformedURLException
     * @throws IOException
     * @throws NoSuchAlgorithmException
     */
    public static JsonSearchResults getSearchResults(String query, String type) throws IOException {

        HashMap<String, Object> parameters = new HashMap();
        parameters.put("query", query);
        parameters.put("type", type);

        String response = JGroove.callMethod(parameters, "getSearchResultsEx");
        return (new Gson().fromJson(response, JsonSearchResults.class));
    }

    /**
     * Returns the songs of the artist given its ID
     * @param artistid ID of the artist
     * @param offset Displacement of the songs (Starting song)
     * @param isverified Songs verified or not
     * @return Json object with all info of the response
     * @throws MalformedURLException
     * @throws IOException
     * @throws NoSuchAlgorithmException
     */
    public static JsonSongs getArtistSongs(String artistid, int offset, boolean isverified) throws IOException {

        HashMap<String, Object> parameters = new HashMap();
        parameters.put("offset", offset);
        parameters.put("artistID", artistid);
        parameters.put("isVerified", isverified);

        String response = JGroove.callMethod(parameters, "artistGetSongs");
        return (new Gson().fromJson(response, JsonSongs.class));
    }

    /**
     * Returns the songs of the album given its ID
     * @param albumid ID of the album
     * @param offset Displacement of the songs (Starting song)
     * @param isverified Songs verified or not
     * @return Json object with all info of the response
     * @throws MalformedURLException
     * @throws IOException
     * @throws NoSuchAlgorithmException
     */
    public static JsonSongs getAlbumSongs(String albumid, int offset, boolean isverified) throws IOException {

        HashMap<String, Object> parameters = new HashMap();
        parameters.put("offset", offset);
        parameters.put("albumID", albumid);
        parameters.put("isVerified", isverified);

        String response = JGroove.callMethod(parameters, "albumGetSongs");
        return (new Gson().fromJson(response, JsonSongs.class));
    }

     /**
     * Returns the songs of the playlist given its ID
     * @param listid ID of the playlist
     * @param offset Displacement of the songs (Starting song)
     * @param isverified Songs verified or not
     * @return Json object with all info of the response
     * @throws MalformedURLException
     * @throws IOException
     * @throws NoSuchAlgorithmException
     */
    public static JsonPlaylistSongs getPlaylistSongs(String listid, int offset, boolean isverified) throws IOException {

        HashMap<String, Object> parameters = new HashMap();
        parameters.put("offset", offset);
        parameters.put("playlistID", listid);
        parameters.put("isVerified", isverified);

        String response = JGroove.callMethod(parameters, "playlistGetSongs");
        return (new Gson().fromJson(response, JsonPlaylistSongs.class));
    }

    /**
     * Returns a list of Popular Songs
     * @param type "monthly" or null to "daily"
     * @return Json Object that contains the list of popular songs
     * @throws IOException
     */
    public static JsonPlaylistSongs getPopularSongs(String type) throws IOException{
        HashMap<String, Object> parameters = new HashMap();
        parameters.put("type", type);

        String response = JGroove.callMethod(parameters, "popularGetSongs");
        return (new Gson().fromJson(response, JsonPlaylistSongs.class));
    }

    /**
     * Must be called before retrieving a stream to avoid Grooveshark to blacklist
     * your IP. All the needed params are given by getSongURL
     * @param servid StreamServerID
     * @param streamkey StreamKey
     * @param songid Song ID
     * @throws IOException
     */
    public static void markSongAsDownloaded(int servid, String streamkey, String songid) throws IOException{
        HashMap<String, Object> parameters = new HashMap();
        parameters.put("streamServerID", servid);
        parameters.put("streamKey", streamkey);
        parameters.put("songID", songid);
        JGroove.callMethod(parameters, "markSongAsDownloadedEx");
    }

     /**
     * Must be called once the stream has finished to avoid Grooveshark to blacklist
     * your IP. All the needed params are given by getSongURL
     * @param servid StreamServerID
     * @param streamkey StreamKey
     * @param songid Song ID
     * @throws IOException
     */
    public static void markSongComplete(int servid, String streamkey, String songid) throws IOException{
        HashMap<String, Object> parameters = new HashMap();
        parameters.put("streamServerID", servid);
        parameters.put("streamKey", streamkey);
        parameters.put("songID", songid);
        JGroove.callMethod(parameters, "markSongComplete");
    }

    /**
     * Returns info about where te get the song stream in a Json Object
     * @param songid The song ID to obtain information about
     * @return JsonGetSong object that contains the streamKey and the IP where
     * to retrieve the song
     * @throws IOException
     */
    public static JsonGetSong getSongURL(String songid) throws IOException{
        HashMap<String, Object> parameters = new HashMap();
        parameters.put("songID", songid);
        parameters.put("country", jgroove.json.JsonPost.country);
        parameters.put("mobile", false);
        parameters.put("prefetch", false);

        String response = JGroove.callMethod(parameters, "getStreamKeyFromSongIDEx");
        return (new Gson().fromJson(response, JsonGetSong.class));
    }

    /**
     * Returns the song audio stream corresponded to the streamKey passed, it can be
     * used to store it on disk or play it.
     * IMPORTANT!: When using this method markSongAsDownloaded and
     * markSongComplete should be used to avoid Grooveshark heuristics to
     * detect this as an attack.
     * @param ip IP of the host where the song is stored
     * @param streamKey streamKey that identifies the song
     * @return Audio stream of the song (InputStream)
     * @throws MalformedURLException
     * @throws IOException
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedAudioFileException
     */
    public static InputStream getSongStream(String ip, String streamKey) throws IOException {
        URL url = new URL("http://"+ ip + "/" + JGroove.streamphp + "?");
        String data = "streamKey=" + streamKey;

        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();

        return conn.getInputStream();
    }
}
